<?php

$choice = 'clear';

$url = 'http://api.giphy.com/v1/gifs/random?api_key=key&tag='.$choice;

// Get the document at this URL
$response = file_get_contents($url);

// Print the raw response for debugging
print_r($response);

include 'db.php';

$obj = new dataobject($_SERVER['REMOTE_ADDR']);

// Decode the response into an object (this is the default behavior of json_decode)
$response = json_decode($response);

// Check if the response contains 'data' and it's an object (not an array)
if (isset($response->data) && is_object($response->data)) {
    // Access the first element of 'data' object directly
    $gif = $response->data;  // Since 'data' is an object, there's no need to index it like an array

    // Ensure 'images' and 'original' are set before accessing them
    if (isset($gif->images->original->url)) {
        $imageUrl = $gif->images->original->url;

        // Set timezone and format date
        date_default_timezone_set('America/New_York');
        $date_time = strftime('%Y-%m-%d %H:%M:%S', time());

        // Connect to the database
        $obj->_setname("name");
        $obj->_setpass("pass");
        $obj->_setconn("conn");
        $obj->connect("connect");

        // Prepare the SQL query to insert the GIF data into the database
        $insertsql = "INSERT INTO localhost (ident, url, date) VALUES (";
        $insertsql .= "'".$gif->id."', '".$imageUrl."', '".$date_time."')";
        
        // Run the query
        $obj->run($insertsql);

        // Optionally print the SQL query for debugging
        // print_r($insertsql);
    } else {
        echo "Error: Missing 'images' or 'original' in the response.";
    }
} else {
    echo "Error: No valid GIF data found in the response.";
}

?>